package com.example.su_shi_tan_home

import android.os.Handler
import android.os.Looper
import android.view.View
import android.widget.AdapterView
import android.widget.ImageView
import android.widget.TextView
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.alibaba.fastjson.JSON
import com.example.library_common.utils.normalShortToast
import com.example.su_shi_tan_bas_lib.adapter.ab_list_adapter.CommonAdapter
import com.example.su_shi_tan_bas_lib.adapter.ab_list_adapter.CommonViewHolder
import com.example.su_shi_tan_bas_lib.base.LazyFragment
import com.example.su_shi_tan_bas_lib.networking.RestClient
import com.example.su_shi_tan_bas_lib.utils.even.MessageWrap
import com.example.su_shi_tan_bas_lib.utils.even.TO_REFRESH_USER_INFO
import com.example.su_shi_tan_bas_lib.utils.even.TO_REFRESH_USER_SIGN_USER_INFO
import com.example.su_shi_tan_bas_lib.utils.timer.BaseTimerTask
import com.example.su_shi_tan_bas_lib.utils.timer.ITimerListener
import com.example.su_shi_tan_bas_lib.view.LabelGridView
import com.example.su_shi_tan_bas_lib.view.LabelListView
import com.example.su_shi_tan_core.arouter.HomeARouter
import com.example.su_shi_tan_core.arouter.MineARouter
import com.example.su_shi_tan_core.bean.SignUserBean
import com.example.su_shi_tan_core.constant.SignUserBeanHolder
import com.example.su_shi_tan_core.db.LogInTokenManager
import com.example.su_shi_tan_core.db.UserInfoBean
import com.example.su_shi_tan_core.db.UserInfoBeanHolder
import com.example.su_shi_tan_core.extentions.startNavigation
import com.example.su_shi_tan_core.getUserInfo
import com.example.su_shi_tan_home.bean.HomeListBean
import com.example.su_shi_tan_home.bean.TanFanBean
import com.example.su_shi_tan_home.fun_config.*
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.core.BasePopupView
import com.lxj.xpopup.interfaces.SimpleCallback
import com.senon.modularapp.util.JssSpannableString
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.flowOn
import java.util.*

/**
 * 首页
 * */
@Route(path = HomeARouter.Home_Fragment)
class HomeFragment : LazyFragment(), AdapterView.OnItemClickListener {


    private val mFunGridView by lazy {
        view?.findViewById<LabelGridView>(R.id.mFunGridView)
    }

    private val tanFanFourStepIcon by lazy {
        view?.findViewById<ImageView>(R.id.tanFanFourStepIcon)
    }

    private var mFunGridViewAdapter: CommonAdapter<FunConfig>? = null

    private val mListViewMsg by lazy {
        view?.findViewById<LabelListView>(R.id.mListViewMsg)
    }

    private var mmListViewMsgAdapter: CommonAdapter<HomeListBean>? = null

    private val mUnActivation by lazy {
        view?.findViewById<TextView>(R.id.mUnActivation)
    }

    private val mTanFanGridView by lazy {
        view?.findViewById<LabelGridView>(R.id.mTanFanGridView)
    }

    private val lightingPop by lazy {
        LightingPop(_mActivity)
    }

    private var mTanFanAdapter: CommonAdapter<TanFanBean>? = null


    override fun getLayoutId() = R.layout.home_fragment_layout

    override fun lazyInit() {
//        userInfo()
        if (LogInTokenManager.tokenManager.haveSignedIn()) {
            userInfo()
            onSignUser()
        }

    }

    override fun initView(view: View) {
        mFunGridViewAdapter = object :
            CommonAdapter<FunConfig>(
                _mActivity,
                funConfigArray(),
                R.layout.home_fun_item_fragment
            ) {
            override fun convert(helper: CommonViewHolder?, item: FunConfig?, position: Int) {
                helper?.setText(R.id.title, item?.title ?: 0)
                    ?.setImageResource(R.id.icon, item?.icon ?: 0)

            }

        }
        mFunGridView?.adapter = mFunGridViewAdapter
        mFunGridView?.onItemClickListener = this

        mmListViewMsgAdapter = object : CommonAdapter<HomeListBean>(
            _mActivity, R.layout.home_list_item_fragment
        ) {
            override fun convert(helper: CommonViewHolder?, item: HomeListBean?, position: Int) {
                helper?.setText(R.id.title_1, item?.title_0 ?: "")
                    ?.setText(R.id.title_0, item?.title_1 ?: "")
                    ?.setText(R.id.unite, item?.unite ?: "")
            }

        }
        mListViewMsg?.adapter = mmListViewMsgAdapter


        val tanFanList = tanFanList()
        mTanFanAdapter = object : CommonAdapter<TanFanBean>(
            _mActivity,
            tanFanList,
            R.layout.home_tan_fan_list_item_fragment
        ) {
            override fun convert(helper: CommonViewHolder?, item: TanFanBean?, position: Int) {
                helper?.setText(R.id.title, item?.title)
                    ?.setText(R.id.title_1, item?.title_0)
                    ?.setViewSelector(R.id.title_1, item?.isUnDone == true)
            }
        }
        mTanFanGridView?.adapter = mTanFanAdapter
        mTanFanGridView?.numColumns = tanFanList.size
        mTanFanGridView?.onItemClickListener = this

        if (LogInTokenManager.tokenManager.haveSignedIn()) {
            tanFanFourStepIcon?.visibility = View.VISIBLE
        } else {
            tanFanFourStepIcon?.visibility = View.GONE
        }
    }

    override fun handMessage(msg: MessageWrap?) {
//        super.handMessage(msg)
        when (msg?.message) {
            TO_REFRESH_USER_INFO -> {
                userInfo()
            }
            TO_REFRESH_USER_SIGN_USER_INFO -> {
                onSignUser()
            }
        }
    }

    private fun onSignUser() {
        val signUser = SignUserBeanHolder.getSignUser()
        mmListViewMsgAdapter?.updateList(homeListBeanList())

        mFunGridViewAdapter?.updateList(funConfigArray())

        val convertSuffix = convertSuffix("${signUser?.total_unactivation_count}")
        mUnActivation?.text = JssSpannableString(_mActivity, convertSuffix)
            .first(convertSuffix)
            .textColor(R.color.text_color_1)
            .backgroundColor(R.color.PrimaryColor)
            .all("\t")
            .backgroundColor(R.color.bg_color_0)
    }

    private fun userInfo() {
        if (LogInTokenManager.tokenManager.haveSignedIn()) {
            tanFanFourStepIcon?.visibility = View.VISIBLE
        } else {
            tanFanFourStepIcon?.visibility = View.GONE
        }


        mTanFanAdapter?.updateList(tanFanList())
        mTanFanGridView?.numColumns = mTanFanAdapter?.count ?: 1

    }


    private fun convertSuffix(suffix: String): String {
        val mCharArray = suffix.toCharArray()
        val stringBuilder = StringBuilder()
        for ((index, e) in mCharArray.withIndex()) {
            if (index != mCharArray.size - 1) {
                stringBuilder.append(e).append("\t\t")
            } else {
                stringBuilder.append(e)
            }
        }
        return stringBuilder.toString()
    }


    override fun onItemClick(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
        when (parent?.id) {
            R.id.mFunGridView -> {
                val item = mFunGridViewAdapter?.getItem(position)

                if(item?.path?.isEmpty()==true){
                    normalShortToast(_mActivity,"暂未开放")
                    return
                }

                if (item?.path == ACTIVE) {
                    if (!item.isSelected) {
                        aboutLighting()
                    }
                    return
                }

                ARouter.getInstance()
                    .build(item?.path)
                    .startNavigation(this)

            }
            R.id.mTanFanGridView -> {
                val item = mTanFanAdapter?.getItem(position)

                if (LogInTokenManager.tokenManager.haveSignedIn()
                    && item?.pagePath != MineARouter.IDENTIFY_VERIFY) {
                    if (!isVerify()) {
                        return
                    }
                }
                ARouter.getInstance()
                    .build(item?.pagePath)
                    .startNavigation(this)

            }
        }
    }

    private fun aboutLighting() {

        RestClient.builder()
            .url(R.string.sign_integral)
            .success {

                lightingPop.data = it
                XPopup.Builder(_mActivity)
                    .hasShadowBg(true)
                    .setPopupCallback(object : SimpleCallback() {
                        override fun onDismiss(popupView: BasePopupView?) {
                            super.onDismiss(popupView)
//                            getSignUser()
                            getUserInfo(_mActivity)
                        }
                    })
                    .asCustom(lightingPop)
                    .show()
            }.failure {
                normalShortToast(_mActivity, R.string.net_work_failed)

            }.error { _, msg ->
                normalShortToast(_mActivity, msg)

            }.build().post()


    }

    private fun isVerify(): Boolean {
        var flag = true
        when (UserInfoBeanHolder.getUserInfoBean()?.verifyStrFlag()) {
            UserInfoBean.unSubmit -> {
                flag = false
                normalShortToast(_mActivity, "请先实名审核")
            }
            UserInfoBean.checking -> {
                flag = false
                normalShortToast(_mActivity, "正在实名审核中，请稍后")
            }
            UserInfoBean.checkedNot -> {
                flag = false
                normalShortToast(_mActivity, " 实名审核未通过，请重新提交")
            }
        }
        return flag
    }


}